package com.axzhengxin.platform.business.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysDeptService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.axzhengxin.platform.business.domain.BizApplyInfo;
import com.axzhengxin.platform.business.service.IBizApplyInfoService;
import com.ruoyi.common.core.page.TableDataInfo;


/**
 * 客户需求Controller
 *
 * @author axzhengxin
 * @date 2021-02-20
 */
@RestController
@RequestMapping("/business/bizApplyInfo")
public class BizApplyInfoController extends BaseController {
    @Autowired
    private IBizApplyInfoService bizApplyInfoService;

    @Autowired
    private ISysDeptService sysDeptService;
    /**
     * 抵押创建
     */
    private String pledgeCreate = "PLEDGE_CREATE";
    /**
     * 抵押解除
     */
    private String pledgeDisable = "PLEDGE_DISABLE";

    /**
     * 查询客户需求列表
     * 添加一个flag用于前端判断当前登录人可以抢单
     */
    @PreAuthorize("@ss.hasPermi('business:bizApplyInfo:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizApplyInfo bizApplyInfo) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (!SecurityUtils.isAdmin(user.getUserId())) {
            Long deptId = user.getDeptId();
            SysDept sysDept = sysDeptService.selectDeptById(deptId);
            List<String> childDeptId = sysDeptService.getAllChildDeptId(deptId);
            String ancestors = sysDept.getAncestors();
            List<String> ancestorsList = Arrays.asList(ancestors.split(","));
            List<String> list = new ArrayList<>();
            for (int i = 1; i < ancestorsList.size(); i++) {
                list.add(ancestorsList.get(i));
            }
            list.add(String.valueOf(deptId));
            list.addAll(childDeptId);
            bizApplyInfo.setDeptIds(list);
        }
        startPage();
        List<BizApplyInfo> bizApplyInfos = bizApplyInfoService.selectApplyInfoList(bizApplyInfo);
        return getDataTable(bizApplyInfos);
    }


    /**
     * 查询待审核订单列表 --查询待分配、待审核列表
     */
    @PreAuthorize("@ss.hasPermi('business:bizApplyInfo:auditingList')")
    @GetMapping("/auditingList")
    public TableDataInfo auditingList(BizApplyInfo bizApplyInfo) {
        startPage();
        List<BizApplyInfo> list = bizApplyInfoService.selectAuditingList(bizApplyInfo);
        return getDataTable(list);
    }

    /**
     * 查询待授信订单列表
     */
    @PreAuthorize("@ss.hasPermi('business:bizApplyInfo:approveList')")
    @RequestMapping("/approveList")
    public TableDataInfo approveList(BizApplyInfo bizApplyInfo) {
        startPage();
        List<BizApplyInfo> list = bizApplyInfoService.selectApproveList(bizApplyInfo);
        return getDataTable(list);
    }

    /**
     * 待放款订单列表查询
     *
     * @param applyInfo 需求对象
     * @return 分页数据
     */
    @PreAuthorize("@ss.hasPermi('business:bizApplyInfo:loanList')")
    @RequestMapping("/loanList")
    public TableDataInfo loanList(BizApplyInfo applyInfo) {
        startPage();
        List<BizApplyInfo> list = bizApplyInfoService.loanList(applyInfo);
        return getDataTable(list);
    }

    /**
     * 担保订单列表
     *
     * @param applyInfo
     * @return
     */
    @PreAuthorize("@ss.hasPermi('business:bizApplyInfo:guaranteeList')")
    @RequestMapping("/guaranteeList")
    public TableDataInfo guaranteeList(BizApplyInfo applyInfo) {
        startPage();
        List<BizApplyInfo> list = bizApplyInfoService.guaranteeList(applyInfo);
        return getDataTable(list);
    }

    /**
     * 抵押订单列表
     *
     * @param applyInfo
     * @return
     */
    @PreAuthorize("@ss.hasPermi('business:bizApplyInfo:pledgeList')")
    @RequestMapping("/pledgeList")
    public TableDataInfo pledgeList(BizApplyInfo applyInfo, Integer flag) {
        if (flag != null) {
            if (flag == 1) {
                applyInfo.setStatus(1010);
                applyInfo.setBizType(pledgeCreate);
            }
            if (flag == 2) {
                applyInfo.setStatus(2000);
                applyInfo.setBizType(pledgeCreate);
            }
            if (flag == 3) {
                applyInfo.setStatus(2000);
                applyInfo.setBizType(pledgeDisable);
            }
        }
        startPage();
        List<BizApplyInfo> list = bizApplyInfoService.pledgeList(applyInfo);
        return getDataTable(list);
    }


    /**
     * 抢单操作
     *
     * @param reqId 需求ID
     * @return
     */
    @PreAuthorize("@ss.hasPermi('business:bizApplyInfo:checkIn')")
    @Log(title = "抢单", businessType = BusinessType.UPDATE)
    @RequestMapping("/checkIn")
    public AjaxResult checkInApply(String reqId) {
        //执行抢单操作 -开启流程
        int code = bizApplyInfoService.checkIn(reqId);
        if (code == 100) {
            return AjaxResult.error("您的部门已经抢单了，无法重发抢单！");
        }
        if (code == 103) {
            return AjaxResult.error("超过最大3家抢单机构，无法继续抢单！");
        }
        if (code == 110) {
            return AjaxResult.error("系统繁忙，请重试");
        }
        if (code == 200) {
            return AjaxResult.success("抢单成功");
        }
        return AjaxResult.error("抢单失败，未知错误！");
    }

    /**
     * 批量抢单
     *
     * @param reqIds 需求IDs
     * @return
     */
    @PreAuthorize("@ss.hasPermi('business:bizApplyInfo:moreCheckIn')")
    @Log(title = "批量抢单", businessType = BusinessType.UPDATE)
    @RequestMapping("/moreCheckIn")
    public AjaxResult moreCheckIn(String[] reqIds) {
        int count = 0;
        int allCount = 0;
        String wrongMsg = "，失败订单对应业务流水号：";
        if (reqIds != null && reqIds.length > 0) {
            for (String reqId : reqIds) {
                int code = bizApplyInfoService.checkIn(reqId);
                allCount++;
                if (code != 200) {
                    count++;
                    wrongMsg += reqId + ",失败原因：";
                    if (code == 100) {
                        wrongMsg += "您的部门已经抢单了，无法重发抢单；";
                    }
                    if (code == 103) {
                        wrongMsg += "超过最大3家抢单机构，无法继续抢单；";
                    }
                    if (code == 110) {
                        wrongMsg += "系统繁忙；";
                    }
                }
            }
        } else {
            return AjaxResult.error("请勾选订单！");
        }
        String msg = "批量抢单完成，共计抢" + allCount + "单，其中抢单失败有" + count + "单";
        if (count > 0) {
            msg += wrongMsg;
        }
        return AjaxResult.success(msg);
    }

    /**
     * 获取需求详情
     *
     * @param bizApplyInfo 需要reqId
     * @return
     */
    @PreAuthorize("@ss.hasPermi('business:bizApplyInfo:getBizApplyInfo')")
    @RequestMapping("/getBizApplyInfo")
    public BizApplyInfo getBizApplyInfo(BizApplyInfo bizApplyInfo) {
        return bizApplyInfoService.getBizApplyInfo(bizApplyInfo);
    }


    /**
     * 获取授信信息
     */
    @PreAuthorize("@ss.hasPermi('business:bizApplyInfo:getApproveInfo')")
    @RequestMapping("/getApproveInfo")
    public BizApplyInfo getApproveInfo(BizApplyInfo bizApplyInfo) {
        return bizApplyInfoService.getApproveInfo(bizApplyInfo);
    }

    /**
     * 撤销需求订单
     *
     * @param reqId
     * @return
     */
    @RequestMapping("/backApply")
    public AjaxResult getApproveInfo(String reqId) {
        return bizApplyInfoService.backApply(reqId);
    }
}
